package com.xipu.yygh.manage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xipu.yygh.common.exception.YyghException;
import com.xipu.yygh.manage.repository.ScheduleRepository;
import com.xipu.yygh.manage.service.DepartmentService;
import com.xipu.yygh.manage.service.HospManageService;
import com.xipu.yygh.manage.service.ScheduleService;
import com.xipu.yygh.model.hosp.BookingRule;
import com.xipu.yygh.model.hosp.Department;
import com.xipu.yygh.model.hosp.Hospital;
import com.xipu.yygh.model.hosp.Schedule;
import com.xipu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.xipu.yygh.vo.hosp.ScheduleOrderVo;
import com.xipu.yygh.vo.hosp.ScheduleQueryVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * description: 排班Service
 * @author: gql
 * @date: 2022/05
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {

    /**
     * 排班信息(MongoDB)
     */
    @Autowired
    private ScheduleRepository scheduleRepository;

    /**
     * 医院表(MongoDB)
     */
    @Autowired
    private HospManageService hospManageService;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 部门表(Mongo)
     */
    @Autowired
    private DepartmentService departmentService;


    @Override
    public void saveSchedule(Map<String, Object> map) {
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(map), Schedule.class);
        if (StringUtils.isEmpty(schedule)) {
            throw new YyghException(20001, "上传数据异常!");
        } else {
            Schedule existSchedule =
                    this.scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
            if (StringUtils.isEmpty(existSchedule)) {
                // 保存
                schedule.setCreateTime(new Date());
            } else {
                // 修改
                schedule.setId(existSchedule.getId());
            }
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
            schedule.setUpdateTime(new Date());
            scheduleRepository.save(schedule);
        }
    }

    @Override
    public Page<Schedule> selectPage(int page, int limit, ScheduleQueryVo scheduleQueryVo) {
        // 1.设置排序规则
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");

        // 2.设置分页数据
        Pageable pageable = PageRequest.of(page - 1, limit, sort);

        // 3.条件匹配器
        ExampleMatcher matcher = ExampleMatcher.matching()
                // 改变默认字符串匹配方式：模糊查询
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                // 改变默认大小写忽略方式：忽略大小写
                .withIgnoreCase(true);

        // 4.将departmentQueryVo转换为department
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        schedule.setIsDeleted(0);

        // 5.封装查询条件
        Example<Schedule> example = Example.of(schedule, matcher);

        // 6.执行查询
        Page<Schedule> pages = this.scheduleRepository.findAll(example, pageable);
        return pages;
    }

    @Override
    public void scheduleRemove(Map<String, Object> map) {
        String hoscode = (String) map.get("hoscode");
        String depcode = (String) map.get("depcode");
        String hosScheduleId = (String) map.get("hosScheduleId");
        if (StringUtils.isEmpty(hoscode) || StringUtils.isEmpty(depcode) || StringUtils.isEmpty(hosScheduleId)) {
            throw new YyghException(20001, "参数传递异常");
        } else {
            Schedule schedule = this.scheduleRepository.getScheduleByHoscodeAndDepcodeAndHosScheduleId(hoscode, depcode, hosScheduleId);
            // 如果不为空才根据id删除
            if (!StringUtils.isEmpty(schedule)) {
                this.scheduleRepository.deleteById(schedule.getId());
            }
        }
    }

    @Override
    public Map<String, Object> getRuleSchedule(long page, long limit, String hoscode, String depcode) {

        // 1. 封装聚合条件对象
        Aggregation agg = Aggregation.newAggregation(
                // 匹配查询条件
                Aggregation.match(Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode)),
                // 使用workDate分组,first相当于加在select后面
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                        // 医生数量
                        .count().as("docCount")
                        // 可预约数量
                        .sum("reservedNumber").as("reservedNumber")
                        // 剩余预约数量
                        .sum("availableNumber").as("availableNumber"),
                // 升序排序
                Aggregation.sort(Sort.Direction.ASC, "workDate"),
                // 分页
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)
        );

        /*
          2. 调用mongoTemplate.aggregate方法实现聚合查询
               参数1:封装聚合条件的对象
               参数2:集合对应的实体类class(输入)
               参数3:返回结果类型的class(输出)

          最终返回的是一个结果集合,需要再次获取到list集合
         */
        AggregationResults<BookingScheduleRuleVo> aggResults =
                this.mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggResults.getMappedResults();

        // 3. 再查询一次为了获取科室排班数据总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode)),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggResults =
                mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();

        // 4. 根据workDate获取到周几进行封装
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            // 获取每个workDate
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            // 转换为周几再封装回去
            bookingScheduleRuleVo.setDayOfWeek(this.getDayOfWeek(new DateTime(workDate)));
        }

        // 5.将查询到的信息设置到map集合result
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleVoList", bookingScheduleRuleVoList);
        result.put("total", total);

        // 6. 设置医院名称信息
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname", this.hospManageService.getHospital(hoscode).getHosname());
        result.put("baseMap", baseMap);
        return result;
    }

    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        // 1.根据医院编号、科室编号、工作日期查询MongoDB
        List<Schedule> scheduleList =
                scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate).toDate());
        // 2.把得到list集合遍历,封装并设置其他值：医院名称、科室名称、日期对应的星期
        scheduleList.forEach(t -> {
            // 设置医院名称
            t.getParam().put("hosname", this.hospManageService.getHospital(t.getHoscode()).getHosname());
            // 设置科室名称
            t.getParam().put("depname", this.departmentService.getDepName(t.getHoscode(), t.getDepcode()));
            // 设置日期对应的星期
            t.getParam().put("dayOfWeek", this.getDayOfWeek(new DateTime(t.getWorkDate())));
        });
        return scheduleList;
    }

    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        // 1.获取预约规则
        BookingRule bookingRule = this.hospManageService.getHospitalByHoscode(hoscode);

        // 2.获取可预约日期分页数据
        IPage iPage = this.getListDate(page, limit, bookingRule);

        // 3.获取每页显示日期数据(有所有日期)
        List<Date> dateList = iPage.getRecords();

        // 4.聚合查询日期是否有号-根据医院编号、科室编号、工作日期
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode)
                .and("workDate").in(dateList);
        Aggregation agg = Aggregation.newAggregation(
                // 匹配
                Aggregation.match(criteria),
                // 分组
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                        // 统计
                        .count().as("docCount")
                        // 剩余预约数求和
                        .sum("reservedNumber").as("reservedNumber")
                        // 可预约数求和
                        .sum("availableNumber").as("availableNumber")
        );
        // 5.调用方法d得到结果
        AggregationResults<BookingScheduleRuleVo> aggregationResults = this.mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);

        // 6.得到数据集合(有所有日期和号源信息)
        List<BookingScheduleRuleVo> scheduleVoList = aggregationResults.getMappedResults();

        // 7.把查询出来的scheduleVoList集合转换为map集合,key是日期,value是日期对应的排班规则
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();

        if (!CollectionUtils.isEmpty(scheduleVoList)) {
            scheduleVoMap = scheduleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate,
                    BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }

        // 7.拿dateList到scheduleVoList进行日期比对,如果日期有排班规则就显示有号,否则显示无号
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        int len = dateList.size();
        for (int i = 0; i < len; i++) {
            // 用每个日期去查询当天的排班规则
            Date date = dateList.get(i);
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            // 如果当天没有排班规则,说明无号
            if (ObjectUtils.isEmpty(bookingScheduleRuleVo)) {
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                // 设置就诊医生人数为0
                bookingScheduleRuleVo.setDocCount(0);
                // 设置科室剩余预约数为-1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            // 当天有号,就设置可预约日期、今天周几
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            bookingScheduleRuleVo.setDayOfWeek(this.getDayOfWeek(new DateTime(date)));

            // 最后一页最后一条记录显示即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if (i == len - 1 && page == iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }

            // 当前预约如果超过了停号时间,不能预约
            if (i == 0 && page == 1) {
                // 停止挂号时间
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                // 如果当天预约时间过了停号时间， 不能预约
                if (stopTime.isBeforeNow()) {
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        // 8. 放到map集合中返回
        Map<String, Object> result = new HashMap<>();
        // 可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());
        // 封装其他数据
        Map<String, String> baseMap = new HashMap<>();
        // 医院名称
        baseMap.put("hosname", this.hospManageService.getHospital(hoscode).getHosname());
        // 科室
        Department department = this.departmentService.getDepartment(hoscode, depcode);
        // 大科室名称
        baseMap.put("bigname", department.getBigname());
        // 科室名称
        baseMap.put("depname", department.getDepname());
        // 月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        // 放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        // 停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;
    }

    @Override
    public Schedule getByScheduleId(String id) {
        Schedule schedule = this.scheduleRepository.getScheduleById(id);
        // 设置医院名称
        schedule.getParam().put("hosname", this.hospManageService.getHospital(schedule.getHoscode()).getHosname());
        // 设置科室名称
        schedule.getParam().put("depname", this.departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));
        // 设置日期对应的星期
        schedule.getParam().put("dayOfWeek", this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
        return schedule;
    }

    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        // 1.获取排班信息
        Schedule schedule = this.getByScheduleId(scheduleId);
        if (ObjectUtils.isEmpty(schedule)) {
            throw new YyghException(20001, "排班数据为空");
        }
        // 2.获取医院信息、医院的预约规则信息
        Hospital hospital = this.hospManageService.getHospital(schedule.getHoscode());
        if (ObjectUtils.isEmpty(hospital)) {
            throw new YyghException(20001, "hospital数据为空");
        }
        BookingRule bookingRule = hospital.getBookingRule();
        if (ObjectUtils.isEmpty(bookingRule)) {
            throw new YyghException(20001, "排班规则数据为空");
        }

        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        // 医院编号
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        // 医院名称
        scheduleOrderVo.setHosname(hospital.getHosname());
        // 科室编号和名称
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepartment(schedule.getHoscode(), schedule.getDepcode()).getDepname());
        // 排班编号
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        // 剩余号数量
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        // 挂号费
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());
        return scheduleOrderVo;
    }

    @Override
    public void updateSchedule(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        this.scheduleRepository.save(schedule);
    }

    /**
     * 获取可预约日期分页数据
     * @param page 当前页
     * @param limit 每页记录数
     * @param bookingRule 预约规则
     * @return IPage<Date>
     */
    private IPage<Date> getListDate(Integer page, Integer limit, BookingRule bookingRule) {
        // 1.获取预约周期
        int cycle = bookingRule.getCycle();
        // 2.获取当天放号时间
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());

        // 3.当前时间过了放号时间 --> 预约周期+1
        if (releaseTime.isBeforeNow()) {
            cycle += 1;
        }

        // 4.获取所有可显示的日期数据
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            DateTime curDateTime = new DateTime().plusDays(i);
            String dateString = curDateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }

        // 5.日期分页,由于预约周期不一样，页面一排最多显示7天数据，多了就要分页显示
        List<Date> pageDateList = new ArrayList<>();
        int start = (page - 1) * limit;
        int end = (page - 1) * limit + limit;
        if (end > dateList.size()) {
            end = dateList.size();
        }
        // 6.将要显示的日期放入pageDateList集合
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }

        // 7.之前使用的是SpirngDate种的Page对象，这里使用mp中的Page对象
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page, 7, dateList.size());
        // 8.放入分页记录列表并返回
        return iPage.setRecords(pageDateList);
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     * @param date 当前日期
     * @param releaseTime 放号时间
     * @return DateTime(当前日期 + 时间)
     */
    private DateTime getDateTime(Date date, String releaseTime) {
        String releaseTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + releaseTime;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(releaseTimeString);
        return dateTime;
    }

    /**
     * 根据日期获取周几数据
     * @param dateTime org.joda.time工具类
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

}
